package com.accountant.travelaccountant;

import java.math.BigInteger;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Toast;

public class Purpose2 extends Activity {

	EditText etPurpose, etAmount;
	Purpose2 purpose2;
	ScrollView scrollViewForPurpose2;
	Purpose2_ListViewAdapter purpose2_ListViewAdapter;
	Button btnSubmit, btnAddDateTimeToPurpose;
	DatabaseOperations_NonActivity databaseOperations;
	ListView listViewForPurpose2;
	ArrayList<String> memberNames;
	ArrayList<String> memberTableAmount;
	String titleToBeReplaced;
	/* Size for the account */
	BigInteger accountTotalSize;
	/* The amount table for amount */
	BigInteger amountTableAmount;
	/* Average for the above amount */
	BigInteger averageOfAmount;
	/* Get all the members in an arraylist */
	ArrayList<String> memberList;
	/* Get all the amounts paid by every member */
	ArrayList<String> memberAmounts;
	/*
	 * Attributes object is having all the details of the text fields as it had
	 * to be entered in to the database
	 */
	ArrayList<String> attributes;
	AlertDialog alertDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.purpose2);
		purpose2 = this;
		memberList=new ArrayList<String>();
		Purpose2_ListViewAdapter.setMemberName(null);
		memberNames = new ArrayList<String>();
		Utils_NotActivity.buttonPressed = true;
		/*
		 * Attributes object is having all the details of the text fields as it
		 * had to be entered in to the database
		 */
		attributes = new ArrayList<String>();

		/* Initializing the listview */
		listViewForPurpose2 = (ListView) findViewById(R.id.listViewForMemberNamesForPurpose2);
		purpose2_ListViewAdapter = new Purpose2_ListViewAdapter(purpose2,
				memberNames);
		listViewForPurpose2.setAdapter(purpose2_ListViewAdapter);

		/* Linking the textfields to their Ids */
		etPurpose = (EditText) findViewById(R.id.editTextforEnteringAPurposeForPurpose2);
		etAmount = (EditText) findViewById(R.id.editTextforEnteringTheAmountForPurpose2);

		/* Creating an object of database operations */
		databaseOperations = new DatabaseOperations_NonActivity(this);

		/* Opening the database */
		databaseOperations.openWriteableDatabase();

		/*
		 * Creating an arraylist of members so that in this all the meber names
		 * come
		 */
		memberNames = new ArrayList<String>();
		memberNames = databaseOperations.retrieveAll(
				DatabaseOperations_NonActivity.getMembertable(),
				new String[] { DatabaseOperations_NonActivity
						.getMembertablemember() },
				DatabaseOperations_NonActivity.getMembertabletitle() + "="
						+ "\""
						+ SessionClass_NonActivity.sessionObject().getTitle()
						+ "\"", null, null, null, null);

		/* Closing the database */
		databaseOperations.closeDatabase();

		if (memberNames.size() == 0) {
			Toast.makeText(getApplicationContext(),
					"At least one member should be added to the account",
					Toast.LENGTH_SHORT).show();
			finish();
		}

		/*
		 * Initialising the adapter with the arraylist so that the drop down
		 * list can have the list of all the members belonging to that title
		 */

		purpose2_ListViewAdapter = new Purpose2_ListViewAdapter(purpose2,
				memberNames);
		listViewForPurpose2.setAdapter(purpose2_ListViewAdapter);
		/* Initialising the button */
		btnSubmit = (Button) findViewById(R.id.submitButtonForPurpose2);

		btnSubmit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				submitButtonCode();
			}
		});

		listViewForPurpose2.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				v.getParent().getParent().getParent()
						.requestDisallowInterceptTouchEvent(true);
				return false;
			}
		});

		btnAddDateTimeToPurpose = (Button) findViewById(R.id.buttonforAddingTimeForPurpose2);
		btnAddDateTimeToPurpose.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showDialogBoxAddDateTime("Add Date and Time",
						"Do you want to add date and time to the purpose");
			}
		});
	}

	/* Adding a date and time in account */
	private void showDialogBoxAddDateTime(String title, String message) {
		/* Firstly we create an object of AlertDialog.Builder */
		AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
		/* Now we initialise its contents */
		dialogBuilder.setTitle(title);
		dialogBuilder.setMessage(message);

		dialogBuilder.setPositiveButton("Add",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

						if (etPurpose.getText().length() == 0) {
							etPurpose.setText(Utils_NotActivity
									.getCurrentDate()
									+ " "
									+ Utils_NotActivity.getCurrentTime());
						} else {
							titleToBeReplaced = etPurpose.getText().toString()
									.replaceAll("\\s+", " ");
							titleToBeReplaced = titleToBeReplaced + " : "
									+ Utils_NotActivity.getCurrentDate() + " "
									+ Utils_NotActivity.getCurrentTime();
							etPurpose.setText(titleToBeReplaced);
						}
						/* Set cursor at the end */
						etPurpose.setSelection(etPurpose.getText().length());
					}
				});
		dialogBuilder.setNegativeButton("Don't Add",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});

		alertDialog = dialogBuilder.create();
		alertDialog.show();
	}

	public void updateToGetAndToGiveColumns() {
		/* Retrieve the size of the Amount Table */
		accountTotalSize = new BigInteger(databaseOperations.retrieve(
				DatabaseOperations_NonActivity.getAmounttable(),
				new String[] { DatabaseOperations_NonActivity
						.getAmounttabletotalmembers() },
				DatabaseOperations_NonActivity.getAmounttabletitle() + "=\""
						+ SessionClass_NonActivity.sessionObject().getTitle()
						+ "\"", null, null, null, null));

		/* Retrieve the amount table amount */
		amountTableAmount = new BigInteger(databaseOperations.retrieve(
				DatabaseOperations_NonActivity.getAmounttable(),
				new String[] { DatabaseOperations_NonActivity
						.getAmounttableamount() },
				DatabaseOperations_NonActivity.getAmounttabletitle() + "=\""
						+ SessionClass_NonActivity.sessionObject().getTitle()
						+ "\"", null, null, null, null));
		/* Calculating the average */
		averageOfAmount = amountTableAmount.divide(accountTotalSize);

		/* Retrieving all the members of the particular account */
		memberList = databaseOperations.retrieveAll(
				DatabaseOperations_NonActivity.getMembertable(),
				new String[] { DatabaseOperations_NonActivity
						.getMembertablemember() },
				DatabaseOperations_NonActivity.getMembertabletitle() + "=\""
						+ SessionClass_NonActivity.sessionObject().getTitle()
						+ "\"", null, null, null, null);

		/* Retrieving all the amounts of the particular accounts */
		memberAmounts = databaseOperations.retrieveAll(
				DatabaseOperations_NonActivity.getMembertable(),
				new String[] { DatabaseOperations_NonActivity
						.getMembertableamount() },
				DatabaseOperations_NonActivity.getMembertabletitle() + "=\""
						+ SessionClass_NonActivity.sessionObject().getTitle()
						+ "\"", null, null, null, null);

		for (int i = 0; i < accountTotalSize.intValue(); i++) {
			/*
			 * Suppose a person has given more then he has to receive from his
			 * friends
			 */
			if ((new BigInteger(memberAmounts.get(i))).intValue() > averageOfAmount
					.intValue()) {
				/* Updating the to get column */
				databaseOperations.updateRow(
						DatabaseOperations_NonActivity.getMembertable(),
						DatabaseOperations_NonActivity.getMembertabletoget(),
						String.valueOf((new BigInteger(memberAmounts.get(i)))
								.intValue() - averageOfAmount.intValue()),
						DatabaseOperations_NonActivity.getMembertabletitle()
								+ "="
								+ "\""
								+ SessionClass_NonActivity.sessionObject()
										.getTitle()
								+ "\" and "
								+ DatabaseOperations_NonActivity
										.getMembertablemember() + "=" + "\""
								+ memberList.get(i) + "\"", null);

				databaseOperations.updateRow(
						DatabaseOperations_NonActivity.getMembertable(),
						DatabaseOperations_NonActivity.getMembertabletogive(),
						String.valueOf(0),
						DatabaseOperations_NonActivity.getMembertabletitle()
								+ "="
								+ "\""
								+ SessionClass_NonActivity.sessionObject()
										.getTitle()
								+ "\" and "
								+ DatabaseOperations_NonActivity
										.getMembertablemember() + "=" + "\""
								+ memberList.get(i) + "\"", null);
			}
			/*
			 * Suppose a person has given less then he has to give to his
			 * friends
			 */
			else if ((new BigInteger(memberAmounts.get(i))).intValue() < averageOfAmount
					.intValue()) {
				/* Updating the to get column */
				databaseOperations.updateRow(
						DatabaseOperations_NonActivity.getMembertable(),
						DatabaseOperations_NonActivity.getMembertabletogive(),
						String.valueOf(averageOfAmount.intValue()
								- (new BigInteger(memberAmounts.get(i)))
										.intValue()),
						DatabaseOperations_NonActivity.getMembertabletitle()
								+ "="
								+ "\""
								+ SessionClass_NonActivity.sessionObject()
										.getTitle()
								+ "\" and "
								+ DatabaseOperations_NonActivity
										.getMembertablemember() + "=" + "\""
								+ memberList.get(i) + "\"", null);

				databaseOperations.updateRow(
						DatabaseOperations_NonActivity.getMembertable(),
						DatabaseOperations_NonActivity.getMembertabletoget(),
						String.valueOf(0),
						DatabaseOperations_NonActivity.getMembertabletitle()
								+ "="
								+ "\""
								+ SessionClass_NonActivity.sessionObject()
										.getTitle()
								+ "\" and "
								+ DatabaseOperations_NonActivity
										.getMembertablemember() + "=" + "\""
								+ memberList.get(i) + "\"", null);
			}
		}
	}

	/* A function to check whether the account was selected or not */
	private boolean checkIfAnyAccountHasBeenSelectedOrNot() {
		if (Purpose2_ListViewAdapter.getMemberName() == null) {
			Toast.makeText(getApplicationContext(), "Select who is paying",
					Toast.LENGTH_SHORT).show();
			return true;
		}
		return false;
	}

	private void submitButtonCode() {
		/* Check for the account being selected or not */
		if (checkIfAnyAccountHasBeenSelectedOrNot()) {
			return;
		}
		/*
		 * Check for if the database does not exist go directly go to front
		 * screen
		 */
		if (Utils_NotActivity.databaseDoesNotExist(getApplicationContext())) {
			Intent intent1 = new Intent(Purpose2.this, FrontScreen.class);
			startActivity(intent1);
			return;
		}

		/* Opening the database */
		databaseOperations.openWriteableDatabase();

		if (etPurpose.getText().toString().equals("")
				&& etAmount.getText().toString().equals("")) {
			Toast.makeText(getApplicationContext(), "Fields are Empty",
					Toast.LENGTH_SHORT).show();
			/* Closing the database */
			databaseOperations.closeDatabase();
			return;
		}

		if (etPurpose.getText().toString().equals("")) {
			Toast.makeText(getApplicationContext(), "Purpose Field is Empty",
					Toast.LENGTH_SHORT).show();
			/* Closing the database */
			databaseOperations.closeDatabase();
			return;
		}

		if (etAmount.getText().toString().equals("")) {
			Toast.makeText(getApplicationContext(), "Amount Field is Empty",
					Toast.LENGTH_SHORT).show();
			/* Closing the database */
			databaseOperations.closeDatabase();
			return;
		}
		
		/*To protect from entering zeroes*/
		if (Integer.parseInt(etAmount.getText().toString())==0) {
			Toast.makeText(getApplicationContext(), "Zero is not a valid amount",
					Toast.LENGTH_SHORT).show();
			/* Closing the database */
			databaseOperations.closeDatabase();
			return;
		}

		/*
		 * code to prevent the crash that happens when we click submit buttton
		 * too many times
		 */
		if (Utils_NotActivity.saveButtonFromBeingPressedTwice()) {
			/*
			 * Adding all the text field values from the screen to put into the
			 * database
			 */
			attributes.add(SessionClass_NonActivity.sessionObject().getTitle());
			attributes.add(Purpose2_ListViewAdapter.getMemberName());
			attributes.add(etPurpose.getText().toString());
			attributes.add(etAmount.getText().toString());
			/***************************************************/
			System.out.println(attributes.size());
			long x = databaseOperations.insertIntoTable(
					DatabaseOperations_NonActivity.getPurposetable(),
					new String[] {
							DatabaseOperations_NonActivity
									.getPurposetabletitle(),
							DatabaseOperations_NonActivity
									.getPurposetablepayingmember(),
							DatabaseOperations_NonActivity
									.getPurposetablepurpose(),
							DatabaseOperations_NonActivity
									.getPurposetableamount() }, attributes);

			if (x == -1) {
				Toast.makeText(
						getApplicationContext(),
						Purpose2_ListViewAdapter.getMemberName()
								+ " has already paid for "
								+ etPurpose.getText().toString(),
						Toast.LENGTH_SHORT).show();
				/* Closing the database */
				databaseOperations.closeDatabase();
				/*
				 * Reinitializing the variables hatever were declared inside
				 * that button
				 */
				attributes = new ArrayList<String>();
				return;
			} else {
				finish();
				/*
				 * If the row is inserted then we need to update the amount for
				 * the member
				 */
				/* For that first retrieve the value */
				BigInteger amount = new BigInteger(databaseOperations.retrieve(
						DatabaseOperations_NonActivity.getMembertable(),
						new String[] { DatabaseOperations_NonActivity
								.getMembertableamount() },
						DatabaseOperations_NonActivity.getMembertabletitle()
								+ "="
								+ "\""
								+ SessionClass_NonActivity.sessionObject()
										.getTitle()
								+ "\" and "
								+ DatabaseOperations_NonActivity
										.getMembertablemember() + "=" + "\""
								+ Purpose2_ListViewAdapter.getMemberName()
								+ "\"", null, null, null, null));

				/* Now need to update the amount with new value */
				amount = amount.add((new BigInteger(etAmount.getText()
						.toString())));
				/* Now we need to update the row */
				@SuppressWarnings("unused")
				int updatedRows = databaseOperations.updateRow(
						DatabaseOperations_NonActivity.getMembertable(),
						DatabaseOperations_NonActivity.getMembertableamount(),
						String.valueOf(amount),
						DatabaseOperations_NonActivity.getMembertabletitle()
								+ "="
								+ "\""
								+ SessionClass_NonActivity.sessionObject()
										.getTitle()
								+ "\" and "
								+ DatabaseOperations_NonActivity
										.getMembertablemember() + "=" + "\""
								+ Purpose2_ListViewAdapter.getMemberName()
								+ "\"", null);

				/* Updating the amount in the amount table */
				memberTableAmount = new ArrayList<String>();
				/* retrieving all the titles */
				memberTableAmount = databaseOperations.retrieveAll(
						DatabaseOperations_NonActivity.getMembertable(),
						new String[] { DatabaseOperations_NonActivity
								.getMembertableamount() },
						DatabaseOperations_NonActivity.getMembertabletitle()
								+ "=\""
								+ SessionClass_NonActivity.sessionObject()
										.getTitle() + "\"", null, null, null,
						null);

				amount = new BigInteger("0");
				/* Adding all the amounts */
				for (String str : memberTableAmount) {
					amount = amount.add((new BigInteger(str)));
				}

				databaseOperations.updateRow(
						DatabaseOperations_NonActivity.getAmounttable(),
						DatabaseOperations_NonActivity.getAmounttableamount(),
						String.valueOf(amount),
						DatabaseOperations_NonActivity.getAmounttabletitle()
								+ "=\""
								+ SessionClass_NonActivity.sessionObject()
										.getTitle() + "\"", null);

				/* Updating the toGet column in the Member Table */
				updateToGetAndToGiveColumns();
				Purpose2_ListViewAdapter.setMemberName(null);
				/* Closing the database */
				databaseOperations.closeDatabase();
				/* Switching back to the4 previous screen */

			}
		}
	}
}
